const express = require("express");
const route = express.Router();
const adminModel = require("../db/model/adminModel") //引入数据库集合
var md5 = require('md5'); //引入md5加密
const {
    jwtEncode,
} = require('../util/jwt.js') //引入设置token的函数


route.post("/login", async (req, res) => {
    //拿到请求体
    const {
        adminName,
        password
    } = req.body

    try {
        //对数据库进行查询
        const findResult = await adminModel.findOne({
            adminName,
            password: md5(password + '123'),
        });

        //如果没查到
        if (!findResult) {
            return res.send({
                code: 10002,
                msg: "登录异常-账号或密码错误",
                data: null
            })
        }

        //查到了
        const token = jwtEncode(findResult.adminName, "666")

        //登录成功以后把数据库当前的用户状态改为1
        await adminModel.updateOne({
            adminName
        }, {
            $set: {
                status: 1
            }
        })


        res.send({
            code: 10000,
            msg: "登录成功",
            data: {
                token
            }
        })

    } catch (e) {
        console.log("登录查询时发生异常", e.message);
        res.send({
            code: 10001,
            msg: "登录查询时发生异常" + e.message,
            data: null
        })
    }

})

module.exports = route;